package com.ming_za.od_updater_sdk.utils;


import com.ming_za.od_updater_sdk.IUpdater;
import com.ming_za.od_updater_sdk.ODUpdater;
import com.ming_za.od_updater_sdk.server_api.APIUrl;
import com.ming_za.od_updater_sdk.exception.UnConnectServerException;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * HTTP请求工具
 */
public class HttpUtils {

    private static final OkHttpClient client = new OkHttpClient();

    /**
     * 发送get请求
     * @param apiUrl 请求url
     * @param param 请求参数
     * @return 返回体
     * @throws IOException IO异常
     */
    public static Response sendGet(APIUrl apiUrl, JsonPackageBuilder param, IUpdater odUpdater) throws IOException {
        return sendGet(apiUrl.getUrl(),param,odUpdater);
    }

    /**
     * 发送get请求
     * @param url 请求url
     * @param param 请求参数
     * @return 返回体
     * @throws IOException IO异常
     */
    public static Response sendGet(String url, JsonPackageBuilder param, IUpdater odUpdater) throws IOException {

        //完整的url
        String completeUrl = odUpdater.getReqProtocol() + "://" + odUpdater.getIp() + url;
        HttpUrl.Builder builder = Objects.requireNonNull(HttpUrl.parse(completeUrl)).newBuilder();

        if (param != null) {
            for (Map.Entry<String, String> entry : param.buildString().entrySet()) {
                builder.addQueryParameter(entry.getKey(), entry.getValue());
            }
        }

        String rURL = builder.build().toString();
        odUpdater.getLogger().debug("尝试发送请求-->" + rURL);

        Request request = new Request.Builder().url(rURL).get().build();

        Response response = client.newCall(request).execute();

        if (response.code() != 200){
            throw new UnConnectServerException("无法连接至服务器->code=" + response.code());
        }

        return response;
    }
}
